﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Net6Shell.Common
{
    /// <summary>
    /// 
    /// </summary>
    public class JwtManager
    {
        /// <summary>
        /// 延迟加载对象
        /// </summary>
        private static readonly Lazy<JwtManager> _lazy =
            new Lazy<JwtManager>(() => new JwtManager(), LazyThreadSafetyMode.PublicationOnly);

        /// <summary>
        /// 单例对象
        /// </summary>
        public static JwtManager Instance => _lazy.Value;
        private JwtManager()
        {
        }
        /// <summary>
        /// 内部创建一个JWT
        /// </summary>
        /// <returns></returns>
        public string CreatJwtToken()
        {
            //登陆成功
            var claims = new Claim[]
                {
                new Claim(ClaimTypes.Name, "client"),
                new Claim("Id","0001"),
                new Claim("UserName", "张三")
                    //不能放敏感信息 
                };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yuanfengchao2022"));
            //issuer代表颁发Token的Web应用程序，audience是Token的受理者
            var token = new JwtSecurityToken(
                issuer: "http://localhost:6060",
                audience: "http://localhost:5000",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(1),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return "Bearer " + jwtToken;
        }
    }

}
